package com.shebao.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.RectangleReadOnly;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.shebao.entity.SBPersonEntity;

/**
 *
 * 个人社保缴费证明 PDF 工具
 *
 * Created by Frank on 2017\12\22 0021.
 */
@Component
public class PersonalProvePDFUtil {

	@Value("${file.outFile}")
	private String outFile;
	
	@Value("${img.waterMark1}")
	private String waterMark1;
	
	@Value("${img.waterMark2}")
	private String waterMark2;
	
    public static void main(String[] args) throws Exception {
        //水印形式（图片）生成PDF
//        imageWaterMark(createPDF());

        //水印形式（文字）生成PDF
//        stringWaterMark(createPDF(), "天恒志远");

        //普通生成
//        createPDF();
//    	createPDF();
        //读文档；
//        readPDF();
    }

    /**
     * 创建PDF 文档
     * @return
     * @throws Exception
     */
    public String createPDF(List<SBPersonEntity> list,String companyMsg) throws Exception {
    	SBPersonEntity personEntity=list.get(0);
        //输出路径
        //DataUtil.createTempPath(".pdf");

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

        String outPath = outFile+"person-"+format.format(new Date())+".pdf";

        //设置纸张
        Rectangle rect = new Rectangle(new RectangleReadOnly(840,600));

        //创建文档实例
        Document doc = new Document(rect);

        //添加中文字体
        BaseFont bfHelvetica = BaseFont.createFont();

        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

        /**
         * 设置字体样式
         */
        //正常
        Font textFont = new Font(bfChinese,11, Font.NORMAL);
        Font numberFontBold = new Font(bfHelvetica,10, Font.NORMAL);
        //二级标题
        Font secondTitleFont = new Font(bfChinese,18,Font.NORMAL);

        //创建输出流
        PdfWriter pdfWriter = PdfWriter.getInstance(doc, new FileOutputStream(new File(outPath)));
        int totalPage = 1;
        pdfWriter.setPageEvent(new PDFPageHelperPerson(totalPage));

        doc.setMargins(0,0,25,1);

        doc.open();
        doc.newPage();

        doc.setMarginMirroringTopBottom(true);

        //设置一共有多少列
        PdfPTable table = new PdfPTable(4);
        //设置列宽
        table.setTotalWidth(new float[]{ 221f, 179f, 200f, 170f});
        //锁定列宽
        table.setLockedWidth(true);


        /**
         * 第一行
         */
        PdfPCell cell;
        Phrase titlePhrase = new Phrase("成都市社会保险个人参保缴费证明", secondTitleFont);
        cell = new PdfPCell(titlePhrase);

        //设置单元格高度
        cell.setMinimumHeight(32);
        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居中
        cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_TOP);
        cell.setBorder(0);
        cell.setColspan(4);
        table.addCell(cell);

        /**
         * 第二行
         */
        Phrase phrase = new Phrase();
        Chunk c1 = new Chunk("姓名：", textFont);
        Chunk c2 = new Chunk("    "+personEntity.getUserName(), textFont);
        phrase.add(c1);
        phrase.add(c2);

        cell = new PdfPCell(phrase);
        //设置单元格高度
        cell.setMinimumHeight(20);
        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居中
        cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_MIDDLE);
        cell.setBorder(0);
        table.addCell(cell);

        phrase = new Phrase();
        c1 = new Chunk("社会保障号码(身份证号)：", textFont);
        c2 = new Chunk("    "+personEntity.getCardId(), textFont);
        phrase.add(c1);
        phrase.add(c2);

        cell = new PdfPCell(phrase);
        //设置单元格高度
        cell.setMinimumHeight(20);
        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居中
        cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_MIDDLE);
        cell.setBorder(0);
        cell.setColspan(3);

        table.addCell(cell);

        /**
         * 第三行
         */
        phrase = new Phrase();
        c1 = new Chunk("验证码：", textFont);
        c2 = new Chunk("   "+personEntity.getCode(), textFont);
        phrase.add(c1);
        phrase.add(c2);

        cell = new PdfPCell(phrase);
        //设置单元格高度
        cell.setMinimumHeight(20);
        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居中
        cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_MIDDLE);
        cell.setBorder(0);
        table.addCell(cell);

        phrase = new Phrase();
        c1 = new Chunk("社保个人编码：", textFont);
        c2 = new Chunk(" "+personEntity.getSocialId(), textFont);
        phrase.add(c1);
        phrase.add(c2);

        cell = new PdfPCell(phrase);
        //设置单元格高度
        cell.setMinimumHeight(20);
        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居中
        cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_MIDDLE);
        cell.setBorder(0);
        cell.setColspan(2);
        table.addCell(cell);

        cell = new PdfPCell(new Phrase("打印时间： "+DateUtil.printDate(), textFont));
        //设置单元格高度
        cell.setMinimumHeight(20);
        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居中
        cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_MIDDLE);

        cell.setBorder(0);
        table.addCell(cell);



        /**
         * 第四行
         */
        cell = new PdfPCell(new Phrase("（一）最近两年成都市城镇职工参保缴费明细", textFont));
        //设置单元格高度
        cell.setMinimumHeight(18);
        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居中
        cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_MIDDLE);

        cell.setBorder(0);
        cell.setColspan(4);
        table.addCell(cell);

        doc.add(table);


        /**
         * 画表格
         */

        // 创建一个有20列的表格
        table = createDataTable();

        /**
         * 设置表头
         */

        //添加中文字体
        Font font = new Font(bfChinese,8,Font.NORMAL);

        Font fontDetail = new Font(bfChinese,8,Font.NORMAL);

        Font fontDetailNumber = new Font(bfChinese,9,Font.NORMAL);

        //第一行
        createHeaderCell(table,new TableHeaderCell("缴费月份",20,2,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("单位编码",20,2,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("城镇职工养老保险",10,1,3,font),false,true);
        createHeaderCell(table,new TableHeaderCell("城镇职工医疗保险",10,1,3,font),false,true);
        createHeaderCell(table,new TableHeaderCell("大病医疗互助补充保险",12,1,3,font),false,true);
        createHeaderCell(table,new TableHeaderCell("生育保险",10,1,3,font),false,true);
        createHeaderCell(table,new TableHeaderCell("失业保险",10,1,3,font),false,true);
        createHeaderCell(table,new TableHeaderCell("工伤保险",10,1,2,font),true,true);

        //第二行
        createHeaderCell(table,new TableHeaderCell("缴费基数",10,1,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("单位缴纳",10,1,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("个人缴纳",10,1,1,font),false,true);

        createHeaderCell(table,new TableHeaderCell("缴费基数",10,1,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("单位缴纳",10,1,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("个人缴纳",10,1,1,font),false,true);

        createHeaderCell(table,new TableHeaderCell("缴费基数",10,1,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("单位缴纳",10,1,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("个人缴纳",10,1,1,font),false,true);

        createHeaderCell(table,new TableHeaderCell("缴费基数",10,1,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("单位缴纳",10,1,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("个人缴纳",10,1,1,font),false,true);

        createHeaderCell(table,new TableHeaderCell("缴费基数",10,1,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("单位缴纳",10,1,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("个人缴纳",10,1,1,font),false,true);

        createHeaderCell(table,new TableHeaderCell("缴费基数",10,1,1,font),false,true);
        createHeaderCell(table,new TableHeaderCell("单位缴纳",10,1,1,font),true,true);

        SBPersonEntity entity =null;
        //模拟数据
        for(int i = 0;i<list.size();i++){
            //分页
//            if (i != 0 && i%30 == 0){
//                doc.add(table);
//                doc.newPage();//创建新的页面
//                table = createDataTable();
//
//            }
        	entity=list.get(i);
        	
            createHeaderCell(table,new TableHeaderCell(entity.getPayDate(),11,1,1,fontDetailNumber));
            createHeaderCell(table,new TableHeaderCell(0==entity.getCompanyId()?"":""+entity.getCompanyId(),11,1,1,fontDetailNumber));
            createHeaderCell(table,new TableHeaderCell(entity.getOldBase(),11,1,1,fontDetailNumber));
            createHeaderCell(table,new TableHeaderCell(entity.getOldCompany(),11,1,1,fontDetailNumber));
            createHeaderCell(table,new TableHeaderCell(entity.getOldPerson(),11,1,1,fontDetailNumber));
            createHeaderCell(table,new TableHeaderCell(entity.getMedicalBase(),11,1,1,fontDetailNumber));
            createHeaderCell(table,new TableHeaderCell(entity.getMedicalCompany(),11,1,1,fontDetailNumber));
            createHeaderCell(table,new TableHeaderCell(entity.getMedicalPerson(),11,1,1,fontDetailNumber));
            createHeaderCell(table,new TableHeaderCell(entity.getSupplyBase(),11,1,1,fontDetailNumber));
            createHeaderCell(table,new TableHeaderCell(entity.getSupplyCompany(),11,1,1,fontDetailNumber));
            createHeaderCell(table,new TableHeaderCell(entity.getSupplyPerson(),11,1,1,fontDetailNumber));
            createHeaderCell(table,new TableHeaderCell(entity.getBirthBase(),11,1,1,fontDetailNumber));
            createHeaderCell(table,new TableHeaderCell(entity.getBirthCompany(),11,1,1,fontDetailNumber));
            createHeaderCell(table,new TableHeaderCell(entity.getBirthPerson(),11,1,1,fontDetailNumber));
            createHeaderCell(table,new TableHeaderCell(entity.getUnemploymentBase(),11,1,1,fontDetailNumber));
            createHeaderCell(table,new TableHeaderCell(entity.getUnemploymentCompany(),11,1,1,fontDetailNumber));
            createHeaderCell(table,new TableHeaderCell(entity.getUnemploymentPerson(),11,1,1,fontDetailNumber));
            createHeaderCell(table,new TableHeaderCell(entity.getHurtBase(),11,1,1,fontDetailNumber));
            createHeaderCell(table,new TableHeaderCell(entity.getHurtCompany(),11,1,1,fontDetailNumber),true,false);

        }

        doc.add(table);


        //最后的提示信息 footer
        Font eightFont = new Font(bfChinese,8, Font.NORMAL);
        table = createDataTable();

        phrase = new Phrase();
        c1 = new Chunk("表格说明：    1、缴费明细表中空格为未缴费或中断缴费。2、缴费明细表中“单位编码”对应的单位名称为："+companyMsg, eightFont);
        phrase.add(c1);

        cell = new PdfPCell(phrase);
        //设置单元格高度
        cell.setMinimumHeight(25);
        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居左
        cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_BOTTOM);
        cell.setBorder(0);
        cell.setColspan(19);
        table.addCell(cell);

        phrase = new Phrase();
        c1 = new Chunk("验证说明：    1、本证明采用电子验证方式，不再加盖红色公章，如需要核对真伪，请登陆http://www.cdhrss.gov.cn，凭本证明左上角的验证码验证。2、本验证码的有效期至  "+DateUtil.printCodeDate()+"。", eightFont);
        phrase.add(c1);

        cell = new PdfPCell(phrase);
        //设置单元格高度
        cell.setMinimumHeight(9);
        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居左
        cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_MIDDLE);
        cell.setBorder(0);
        cell.setColspan(19);
        table.addCell(cell);


        phrase = new Phrase();
        c1 = new Chunk("                            3、本证明复印件有效，有效期内验证码可多次使用。4、验证码由个人妥善保管，慎防泄漏。5、咨询电话： 12333", eightFont);
        phrase.add(c1);

        cell = new PdfPCell(phrase);
        //设置单元格高度
        cell.setMinimumHeight(9);
        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居左
        cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_MIDDLE);
        cell.setBorder(0);
        cell.setColspan(19);
        table.addCell(cell);

        phrase = new Phrase();
        c1 = new Chunk("特别申明： 成都市社会保险参保查询专用章经四川省数字证书认证管理中心认证，与红色公章具有同样的法律效力。", eightFont);
        phrase.add(c1);

        cell = new PdfPCell(phrase);
        //设置单元格高度
        cell.setMinimumHeight(9);
        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居左
        cell.setHorizontalAlignment(Rectangle.ALIGN_LEFT);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_MIDDLE);
        cell.setBorder(0);
        cell.setColspan(19);
        table.addCell(cell);

        doc.add(table);

        doc.close();
        return imageWaterMark(outPath);
    }



    /**
     * 创建表头单元格和数据
     * @param table 表格对象
     * @param head 表头单元格
     */
    private void createHeaderCell(PdfPTable table,TableHeaderCell head) throws DocumentException, IOException {
    	createHeaderCell(table, head,false,false);
    }
    private void createHeaderCell(PdfPTable table,TableHeaderCell head,boolean isRight,boolean isTop) throws DocumentException, IOException {

        if (head == null || table == null){
            return ;
        }

        PdfPCell cell;
        //这里通过Phrase 居中
        Phrase phrase = new Phrase(head.getContent(), head.getFont());

        cell = new PdfPCell(phrase);

        //设置border
        table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);


        //设置单元格高度
        cell.setMinimumHeight(head.getCellHeight());

        //设置可以居中
        cell.setUseAscender(true);
        //设置水平居中
        cell.setHorizontalAlignment(Rectangle.ALIGN_CENTER);
        //设置垂直居中
        cell.setVerticalAlignment(Rectangle.ALIGN_MIDDLE);
        
        if(!isRight){
        	cell.disableBorderSide(8);// 隐藏单元格周边的右框
        }
        if(!isTop){
        	cell.disableBorderSide(1);// 隐藏单元格周边的上边框
        }
        
        //设置该单元格横跨的行数
        cell.setRowspan(head.getRowspan());
        //设置该单元格横跨的列数
        cell.setColspan(head.getColspan());

        table.addCell(cell);

    }


    /**
     * 加公章的水印
     *
     * @param inputFile 需要加水印的PDF路径
     */
    public String imageWaterMark(String inputFile) {
    	String outputFile=null;
    	PdfReader reader=null;
    	PdfStamper stamper=null;
        try {
            //加公章的水印
            String[] spe = PDFDataUtil.separatePath(inputFile);
            outputFile = spe[0] + "_WM." + spe[1];
            reader = new PdfReader(inputFile);
            stamper = new PdfStamper(reader, new FileOutputStream(outputFile));

            int total = reader.getNumberOfPages() + 1;

            Image image = Image.getInstance(waterMark1);
            //坐标
            image.setAbsolutePosition(638, 455);
            //自定义大小
            image.scaleAbsolute(195,195);
            //image.setRotation(-20);//旋转 弧度
            //image.setRotationDegrees(-45);//旋转 角度
            //依照比例缩放
            image.scalePercent(79);

            PdfGState gs = new PdfGState();
            // 设置透明度为0.2
            gs.setFillOpacity(0.5f);


            
            
            PdfContentByte under = stamper.getUnderContent(1);
            under.beginText();
            // 添加水印图片
            under.addImage(image);
            under.setGState(gs);
            
            
            PdfGState gs1 = new PdfGState();
            gs1.setFillOpacity(10f);
            
            Map<Integer, Integer> map=new HashMap<Integer, Integer>();
            map.put(60, 500);
            map.put(360, 480);
            map.put(120, 250);
            map.put(400, 280);
            map.put(570, 300);
            map.put(327, 92);
            map.put(625, 115);
            for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            	   Image image1 = Image.getInstance(waterMark2);
                   image1.setAbsolutePosition(entry.getKey(), entry.getValue());
                   image1.scaleAbsolute(50,50);
                   image1.scalePercent(26);
                   
                   under.addImage(image1);
                   under.setGState(gs1);
            }
            
            
            
            stamper.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
        	if(null!=stamper){
                try {
					stamper.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
        	}
        	if(null!=reader){
                try {
                	reader.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
        	}
		}
        return outputFile;
    }

    public PdfPTable createDataTable() throws Exception{
        // 创建一个有4列的表格
        PdfPTable table = new PdfPTable(19);
        //设置列宽
        table.setTotalWidth(new float[]{47.7734f,38.095238f,38.095238f,38.786533f,38.095238f,38.786533f,38.095238f,38.786533f,38.786533f,38.095238f,38.786533f,38.786533f,38.095238f,38.786533f,38.40394f,38.40394f,38.40394f,58.451557f,48.0821f});
        //锁定列宽
        table.setLockedWidth(true);

        return table;
    }




}

